﻿using RAP.Framework.Libary.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace RAP.Framework.Libary.SqlTaskParser.Parsers
{
	/// <summary>
	/// @using解析器，指定当前指令之后的SQL语句查询的数据源和是否开启数据库事务
	/// </summary>
	public class UsingTokenParser : ExpressionTokenParser
	{
		/// <summary>
		/// 开启数据库事务的token
		/// </summary>
		private const string TOKEN_PARAM_TRANSACTION = "trans";

		/// <summary>
		/// 默认数据源的token
		/// </summary>
		private const string DEFAULT = "default";

		public override void ParseToken( SqlParseContext context )
		{
			//处理数据源标识 @using;
			var dataSourceId = context.DefaultDataSourceId;
			var sqlToken = context.CurrentToken;
			var needTrans = false;
			if ( sqlToken.Param.IsNotNullOrEmpty() )
			{
				var paramList = sqlToken.Param.Trim().Split( ',' );
				if ( paramList.Length > 0 )
				{
					void parseTokenParam( string param )
					{
						if ( param.IsNotNullOrEmpty() )
						{
							param = param.Trim();
							switch ( param )
							{
								case TOKEN_PARAM_TRANSACTION:
									//处理数据库事务参数
									needTrans = true;
									break;

								default:
									//处理数据源参数
									dataSourceId = param.Equals( DEFAULT ) ? context.DefaultDataSourceId : param;
									break;
							}
						}
					};

					for ( int i = 0; i < paramList.Length; i++ )
					{
						parseTokenParam( paramList[ i ] );
					}
				}
			}
			var currentTask = ( context.CurrentTask != null ? context.CurrentTask : context.CreateSqlTask() );
			currentTask.Trans = needTrans;
			currentTask.DataSourceId = dataSourceId;
		}
	}
}
